package com.lock.redsession.lockredsession.controller;

import com.lock.redsession.lockredsession.bean.Product;
import com.lock.redsession.lockredsession.service.ProductService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@RequestMapping("/product")
@RestController
public class ProductController {

    //注入
    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    private ProductService service;

    /**
     * 需求：减扣库存
     * @return
     */
    @RequestMapping("/decr")
    public boolean decrstockCount(Integer productId){
        // redis分布式锁的key
        String key = "dec_store_lock_" + productId;
        //获取锁对象（获取不到锁就好阻塞）
        RLock lock = redissonClient.getLock(key);
        try {
            //加锁 操作很类似Java的ReentrantLock机制
            lock.lock(2, TimeUnit.MINUTES);
            Product product = service.getProductById(productId);

            //如果库存为空
            if (product.getProductStock()<=0) {
                System.out.println("lock票已售完！");
                return false;
            }
            //简单减库存操作 没有重新写其他接口了
            product.setProductStock(product.getProductStock()-1);
            System.out.println("已购票："+Thread.currentThread()+"::"+product.getProductId()+"票号");
            System.out.println("还剩余："+product.getProductStock()+"张票");
            //更新库存
            service.saveProduct(product);

        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            //解锁
            lock.unlock();
        }

        return true;
    }

}
